<?php
/**
 * @name 用户--数据
 */
namespace app\open\model;
use app\common\model\OpenBase;

class User extends OpenBase {
    protected $http_code = 200;
	protected $tableName = 'user'; //user信息表
	//定义字段信息
	protected $fields = [
		0 => 'uid',
		1 => 'uname',
		2 => 'ticket',
		3 => 'use_status',
		4 => 'usid',
		5 => 'create_time',
		6 => 'last_save_time',
        7 => 'sex',
        8 => 'is_del',
		'_pk' => 'uid',
	];

	//初始化方法
	protected function _initialize() {}

	/**
	 * @name 创建api权限数据
	 * @access protected
	 * @param int $uid 用户uid
	 * @return array 权限数据
	 */
	protected function _createTicket($length = 10, $uid = 0) {
		$length = ($length > 0 && $length <= 32) ? $length : 10;
		$ticket = self::_createCode($length);
		if ($this->where(['ticket' => $ticket])->count > 0) {
			return self::_createTicket($length, $uid);
		}
		if ($uid) {
			$this->where('uid=' . $uid)->setField('ticket', $ticket);
		}
		return $ticket;
	}

	/**
	 * @name 取得权限数据
	 * @access protected
	 * @param int or string $uid 用户uid
	 * @return array 权限数据
	 */
	protected function _getTicket($uid = 0, $ticket = '') {
		if (!$uid) {
			//用户不存在
			$this->error = 'not find user';
			return false;
		}
		if (!$ticket) {
			$ticket = $this->getFieldByUid($uid, 'ticket');
		}
		if ($ticket) {
			$return = 'y-' . jiami($ticket . 'i' . $uid);
		} else {
			$this->error = 'Create ticket error,please try again later.';
			$return = false;
		}
		return $return;
	}
    public function t_getticket($uid = 0){
        return $this->_getTicket($uid);
    }
	/**
	 * @name 检测ticket的有效性
	 */
	protected function _checkTicket($ticket = '') {
		if ($ticket) {
			$start = substr($ticket, 0, 2);
			if ($start !== 'y-') {
				$this->error = 'This ticket is illegal.';
				return false;
			}
			$ticket = jiemi(substr($ticket, 2));
            
            if(!model('Valid')->isString($ticket)){
                $this->error = 'This ticket is illegal.';
				return false;
            }
			//$info = explode('i', $ticket, 2);
			$uid = strrchr($ticket, 'i');
			$map = [
				'ticket' => str_replace($uid, '', $ticket),
				'uid' => substr($uid, 1),
			];
			if ($this->where($map)->count() <= 0) {
				$this->error = 'This ticket is illegal.';
				return false;
			}
			return $map;
		}
		$this->error = 'This ticket is illegal.';
		return false;
	}
	/**
	 * @name 添加用户
	 */
	public function addUser($data = []) {
		
		//检测用户是否已经存在
		$uid = $this->getFieldByUsid($data['usid'], 'uid');
		
        $ticket = self::_createTicket(10);
		if ($uid) {
			//参数检测
			if (true !== self::validParams($data, 'save')) {
				return false;
			}
            $save = [];
            if($data['uname'] && $this->getUsername($uid) != $data['uname']){
                $save['uname'] = $data['uname'];
            }
            if($data['sex'] && $this->getUserSex($uid) != $data['sex']){
                $save['sex'] = $data['sex'];
            }
            if(isset($data['ticket'])){
                $save['ticket'] = $ticket;
            }
            if(!empty($save)){
                $where = ['uid' => $uid];
                $save['last_save_time'] = NOW_TIME;
                if(!M('user')->where($where)->save($save)){
                     $this->error = 'Update user has error:failed to edit, please try again later';
                     $this->http_code = 500;
			         return false;
                }
            }
			//自动修复授权表信息
			model('open/UserAuth')->getAuthdata($uid, true);
			return $this->_getTicket($uid);
		}
		//参数检测
		if (true !== self::validParams($data, 'add')) {
			return false;
		}
		$addUser = [
			'usid' => $data['usid'],
			'uname' => $data['uname'],
			'ticket' => $ticket,
            'sex' => $data['sex'],
			'create_time' => NOW_TIME,
		];
		if ($uid = $this->add($addUser)) {
			//自动修复IM用户
			//$data = array_merge($addUser, ['uid' => $uid]);
			model('open/UserImAccount')->getImUser($uid);
			model('open/UserAuth')->getAuthdata($uid, true);
			return $this->_getTicket($uid, $ticket);
		} else {
			$this->error = 'Add user has error:failed to add, please try again later';
            $this->http_code = 500;
			return false;
		}

	}
	/**
	 * @name 创建一个IM用户
	 */
	public function imUserAdd($data = []) {
		//生成密码
		//$data['im_uid'] = getImUID($data['uid']);
		//$data['password'] = md5($data['im_uid'] . self::_createCode(20));
		//return model('open/UserImAccount')->getImUser($data);
	}
	/**
	 * 参数验证方法
	 */
	protected function validParams($data = [], $type = 'add') {
		switch ($type) {
			case 'add':
				if (!$data['usid'] || !$data['uname']) {
					$this->error = 'Add user has error:your params must contain usid and uname';
                    $this->http_code = 400;
					return false;
				}
				break;

			case 'save':
				if (!$data['usid'] && !$data['ticket']) {
					$this->error = 'Edit user has error:your params must contain usid or ticket';
                    $this->http_code = 400;
					return false;
				}
				break;
			default:
				break;
		}
		return true;
	}
	/**
	 * 检测是否已经有用户存在
	 */
	public function hasUser($map = []) {
		return $this->where($map)->count() > 0 ? true : false;
	}
	/**
	 * @name 通过用户信息票据兑换用户授权信息
	 */
	public function getUserAuthByTicket($ticket = '') {
		$return = [];
		if ($ticket) {
			$res = self::_checkTicket($ticket);
			if ($res === false) {
				return false;
			}
			$uid = $res['uid'];
            $usid = $this->getUsidByUid($uid);
            if(!$usid){
                return ['code' => '10404', 'message' => 'Not find user by ticket.'];
            }
			//IM账号信息
			$imUser = model('open/UserImAccount')->getImUser($uid);
			$return['im'] = (object) $imUser;
			$return = array_merge($return, model('open/UserAuth')->getAuthdata($uid, false));
			$return['usid'] = $usid;
            //yzs1013
            //$return['usid']="ThinkSNS_4364";
            //$return['ak']="put19b05b5cf8f96818d5bd86f95put1";
            model('open/UserData')->syncData($uid);
		}
		if (!empty($return)) {
			return ['code' => '00000', 'data' => $return];
		}
		return ['code' => '10401', 'message' => 'This ticket is illegal.'];
	}

	/**
	 * @name 更新单个字段信息
	 * @access public
	 * @param string $field 需要更新的字段
	 * @param string $value 字段值
	 * @param array $map 条件
	 * @return int 受影响的条数
	 */
	public function updateField($field, $value, $map) {
	     $fields[$field] = $value;
         $fields['last_save_time'] = NOW_TIME;
		 $this->where($map)->save($fields);
	}
	/**
	 * @name 获取用户昵称
	 */
	public function getUsername($uid = 0) {
		if ((int) $uid) {
			return $this->getFieldByUid($uid, 'uname') ?: '';
		}
		return '';
	}
    /**
	 * @name 获取用户性别
	 */
	public function getUserSex($uid = 0) {
		if ((int) $uid) {
			return (int)$this->getFieldByUid($uid, 'sex') ?: 0;
		}
		return '';
	}
	/**
	 * @name 获取用户的usid
	 */
	public function getUsidByUid($uid = 0) {
		if ((int) $uid) {
			//return $this->getFieldByUid($uid, 'usid') ?: '';
			return $this->where(['uid'=>$uid,'is_del'=>0])->getField('usid') ?: '';
		}
		return '';
	}
	/**
	 * @name 获取用户的usid
	 */
	public function getUidByUsid($usid = '') {
		if ($usid) {
			return $this->getFieldByUsid($usid, 'uid') ?: 0;
		}
		return 0;
	}
	/**
	 * @name 获取用户信息
	 */
	public function getUserInfo($uid = 0) {
		if ($uid) {
			return [
				'usid'  => $this->getUsidByUid($uid),
				'uname' => $this->getUsername($uid),
                'sex'   => $this->getUserSex($uid),
			];
		} else {
			return [];
		}
	}
    /**
	 * @name 在指定用户集合中进行性别分类
	 * @access public
	 * @param array $uids 用户UID数组
	 * @param int sex 筛选的性别  0:不限制  1:男  2:女
	 * @return array 筛选后的UID数组
	 */
	public function getFilterForSex($uids = [], $sex = 0) {
		if (empty($uids) || !$sex) {
			return $uids;
		}
		$uids = $this->where(['uid' => ['in', $uids], 'sex' => $sex])->select();
		return getSubByKey($uids, 'uid');
	}
    
    /**
     * @name 获取httpcode
     */
    public function getHttpCode(){
        return $this->http_code;
    }
    /**
     * @name 删除一个用户
     */
    public function deleteUserByUid($uid = 0){
        if($uid){
            //删除用户
            if($count = $this->where(['uid'=>$uid])->delete()){
                //删除用户统计
                model('open/UserData')->where(['uid'=>$uid])->delete();
                //删除授权
                model('open/UserAuth')->where(['uid'=>$uid])->delete();
                //删除直播间
                model('stream/Stream')->where(['uid'=>$uid])->setField('is_del',1);
                //删除IM账号
                model('open/UserImAccount')->where(['local_uid' => $uid,'is_admin' => 0])->delete();
		// delete video
		model('stream/Video')->where(['uid' => $uid])->delete();
                return $count;
            }
        }
        return false;
    }
}
